<template>
  <view class="list">
    <s-pull-scroll ref="pullScroll" :back-top="true" :fixed="fixed" :pullDown="pullDown" :pullUp="loadData">
      <slot></slot>
    </s-pull-scroll>
  </view>
</template>

<script>
import sPullScroll from "../../s-pull-scroll/index.vue";
export default {
  components: {
    "s-pull-scroll": sPullScroll
  },
  props: {
    fixed: {
      type: Boolean,
      default() {
        return false;
      }
    },
    fetchData: {
      type: Function,
      default: null
    },
    pageSize: {
      type: Number,
      default: () => 10
    },
    auto: {
      type: Boolean,
      default() {
        return true;
      }
    }
  },
  data() {
    return {
      pageNum: 0,
      isReset: false,
      pullScroll: null
    };
  },
  mounted() {
    if (this.auto) this.refresh();
  },
  methods: {
    reset() {
      this.refresh();
    },
    refresh() {
      this.pageNum = 0;
      this.$nextTick(() => {
        this.$refs.pullScroll.refresh();
      });
    },
    pullDown(pullScroll) {
      this.isReset = true;
      this.pageNum = 0;
      this.pullScroll = pullScroll;
      setTimeout(() => {
        this.loadData(pullScroll);
      }, 200);
    },
    loadData(pullScroll, isReset) {
      this.pageNum++;
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      if (!this.fetchData) {
        this.pullScroll.empty();
        return;
      }
      this.fetchData(params, isReset || this.isReset)
        .then(res => {
          let { count } = res;
          this.isReset = false;
          if (this.pullScroll) {
            if (count == 0) this.pullScroll.empty();
            this.pullScroll.success();
            if (this.pageNum * this.pageSize >= count) {
              this.pullScroll.finish(true);
            }
          }
        })
        .catch(err => {
          if (this.pullScroll) {
            this.pullScroll.error();
          }
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.list {
  height: 100%;
}
.scroll-view {
  height: 100%;
  /* position: absolute; */
  // .refresh-status-bar {
  //   // margin-top: -40px;
  // }
}
.tip {
  height: 100upx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999999;
  font-size: 28upx;
}
</style>
